<?php
namespace Sys\Controller;
use Common\Controller\BaseController;
class RoleController extends BaseController{
	public $mname;
	public $notHave;
	
	public function __construct(){
		parent::__construct();
	}
	public function index(){
		$res = M('roles')->select();
		$this-> assign('roles', $res);
		$this->display();
	}

	public function doDelRole(){
		$ids = I('post.ids');
		$taf = M('roles')-> delete($ids);
		if(!$taf){
			$msg = [
				'msg' 	=> '删除失败',
				'error' => 0,
			];
		}
	}

	public function jump(){
		$id = M('roles')->data($_GET)->add();
		header('Location:'.U('editRoles',['role_id'=>$id]));
		
        
		
	}
	public function lastId(){
		$lastId=M('roles')->max('role_id');
		$this->ajaxReturn($lastId);
}
public function editRoles(){
		$where = [
			'role_id' => I('get.role_id'),
		];
		$res = M('roles') ->field('menu_ids') ->where($where)-> find();
		$resArr = explode(',',$res['menu_ids']);
		foreach($resArr as $v){
			$this-> mname[$v] = M('menus')-> getFieldBymenu_id($v,'mname');
		}
		$menu_ids = M('menus')-> field('menu_id')-> select();
		foreach($menu_ids as $k => $v){
			$menuAll[$k] = $v['menu_id'];
		}
		$diff = array_diff($menuAll,$resArr);
		foreach($diff as $v){
			$this-> notHave[$v] = M('menus')-> getFieldBymenu_id($v,'mname');
		}
		$this-> assign('notHave',$this-> notHave);
		$this-> assign('roleName',$this-> mname);
		$this-> display();
	}
	public function doEditRoles(){
		$index = (I('get.id'));
		$where = [
			'role_id' => I('get.role_id'),
		];
		$temporary = M('roles')-> field('menu_ids') ->where($where) ->find();
		$str = sprintf(",%s,",$temporary['menu_ids']);
		$regex = '/(,'.$index.',)|(^'.$index.',)|(,'.$index.'$)/';
		$case = preg_match($regex,$str);
		if($case){
			$str = preg_replace($regex,',',$str);
		}else{
			$str .=($index.',');
		}
		$str = substr($str,1,-1);
		//dump($str);
		$data = [
			'role_id' => I('get.role_id'),
			'menu_ids'=> $str,
		];
		M('roles')-> save($data);
	}
}
